extends Node
class_name EconomyManager

signal gold_changed(new_amount)
signal experience_changed(new_amount)
signal level_changed(new_level)

@export var starting_gold: int = 10
@export var base_income: int = 5
@export var interest_rate: float = 0.1
@export var max_interest: int = 5
@export var streak_bonus: int = 1
@export var max_streak_bonus: int = 3
@export var loss_streak_bonus: int = 2

var current_gold: int = 0
var current_level: int = 1
var current_experience: int = 0
var win_streak: int = 0
var loss_streak: int = 0

var experience_per_level = [0, 2, 4, 8, 12, 16, 20, 24, 32]

func _ready():
	current_gold = starting_gold
	emit_signal("gold_changed", current_gold)
	emit_signal("level_changed", current_level)

func calculate_round_income(won_round: bool) -> int:
	var income = base_income
	
	# Interest calculation
	var interest = min(int(current_gold * interest_rate), max_interest)
	income += interest
	
	# Streak calculation
	if won_round:
		win_streak += 1
		loss_streak = 0
		income += min(win_streak * streak_bonus, max_streak_bonus)
	else:
		loss_streak += 1
		win_streak = 0
		income += min(loss_streak * loss_streak_bonus, max_streak_bonus * 2)
	
	return income

func add_gold(amount: int):
	current_gold += amount
	emit_signal("gold_changed", current_gold)

func spend_gold(amount: int) -> bool:
	if current_gold >= amount:
		current_gold -= amount
		emit_signal("gold_changed", current_gold)
		return true
	return false

func add_experience(amount: int):
	current_experience += amount
	emit_signal("experience_changed", current_experience)
	check_level_up()

func check_level_up():
	if current_level < experience_per_level.size() - 1:
		if current_experience >= experience_per_level[current_level]:
			current_experience -= experience_per_level[current_level]
			current_level += 1
			emit_signal("level_changed", current_level)
			emit_signal("experience_changed", current_experience)

func buy_experience(amount: int = 4) -> bool:
	var cost = 4
	if spend_gold(cost):
		add_experience(amount)
		return true
	return false

func get_max_units() -> int:
	return current_level

func get_experience_to_next_level() -> int:
	if current_level < experience_per_level.size() - 1:
		return experience_per_level[current_level]
	return 999

func reset():
	current_gold = starting_gold
	current_level = 1
	current_experience = 0
	win_streak = 0
	loss_streak = 0
	emit_signal("gold_changed", current_gold)
	emit_signal("level_changed", current_level)
	emit_signal("experience_changed", current_experience)